package com.quanyan.club.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.response.RespActivityPoster;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.constants.ClubSearchConstants;
import com.quanyan.club.entity.*;
import com.quanyan.club.entity.RespClubActivity;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.ReqClubActivityCondition;
import com.quanyan.club.entity.vo.req.ReqClubActivitySearch;
import com.quanyan.club.entity.vo.req.ReqClubPage;
import com.quanyan.club.entity.vo.req.ReqClubSearch;
import com.quanyan.club.entity.vo.resp.*;
import com.quanyan.club.entity.vo.resp.RespSearchActivity;
import com.quanyan.club.mapper.*;
import com.quanyan.club.pullclub.utils.StringUtils;
import com.quanyan.club.service.*;
import com.quanyan.club.util.ActivityUtils;
import com.quanyan.club.util.NumberGenerator;
import com.quanyan.comment.serviceFacade.UserCollectServiceFacade;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.constants.SearchConstants;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.PlaceDubboProvider;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.search.utils.Constant;
import com.quanyan.user.response.RespOpenUserInterest;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhang on 16/5/31.
 */
@Service("clubOpenService")
public class ClubOpenServiceImpl implements ClubOpenService {
    private static final Logger logger = LoggerFactory.getLogger(ClubOpenServiceImpl.class);
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Autowired
    private TbClubMemberApplyMapper clubMemberApplyMapper;
    @Autowired
    private TbClubAnnouncementUidRelationMapper clubAnnouncementUidRelationMapper;
    @Autowired
    private TbClubAnnouncementMapper clubAnnouncementMapper;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private ClubOpenExtendMapper clubOpenExtendMapper;
    @Autowired
    private ClubFinanceMgmService clubFinanceMgmService;
    @Autowired
    private ClubAccountService clubAccountService;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private TbActivityPosterMapper tbActivityPosterMapper;
    @Autowired
    private ClubService clubService;
    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private TbSignUserMapper signUserMapper;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private TbClubActivityMapper tbClubActivityMapper;
    @Autowired
    private PlaceClient placeClient;
    @Autowired
    private TbClubActivitySettlementMapper clubActivitySettlementMapper;
    @Autowired
    private TbClubActivitySettlementDetailMapper clubActivitySettlementDetailMapper;
    @Autowired
    private TbClubMapper tbClubMapper;

    @Autowired
    private UserCollectServiceFacade userCollectServiceFacade;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ClubActivityService clubActivityService;

    @Autowired
    private ClubActivityMapper clubActivityMapper;

    @Value("${search.cloud.url}")
    public String searchCloudUrl;

    @Autowired
    private TbActivityMapper tbActivityMapper;
    @Autowired
    private ClubActivityCRUDMapper clubActivityCRUDMapper;
    @Autowired
    private ActivityCRUDService activityCRUDService;
    @Autowired
    private ClubSearchBizService clubSearchBizService;
    @Autowired
    private TbActivityDescMapper tbActivityDescMapper;
    @Autowired
    private ClubHomePageService clubHomePageService;
    @Autowired
    private ActivitySupportService activitySupportService;
    @Autowired
    private TbClubIntegralRuleMapper tbClubIntegralRuleMapper;

    public Map<Integer, List<Integer>> queryActivityWeekByClubs(List<Integer> clubIds) {
        long start = System.currentTimeMillis();
        Map<Integer, List<Integer>> clubMaps = new HashMap<Integer, List<Integer>>();
        for (Integer clubId : clubIds) {
            clubMaps.put(clubId, clubSearchBizService.getActivityWeekDays(clubId));
        }
        long end = System.currentTimeMillis();
        logger.warn("-----计算时间-------------" + (end - start) + "------------------");
        return clubMaps;
    }

    public List<RespSearchActivity> selectActivityByClub(double lat, double lng,
            int clubId, int pageSize) {
        long start = System.currentTimeMillis();
        logger.warn("selectActivityByClub入参：" + lat + "," + lng + "," + clubId);
        ReqClubActivityCondition reqClubActivityCondition = new ReqClubActivityCondition();
        reqClubActivityCondition.setClubId(clubId);
        reqClubActivityCondition.setPageNum(0);
        reqClubActivityCondition.setPageSize(pageSize);
        reqClubActivityCondition.setStatus(6);
        reqClubActivityCondition.setLat(lat);
        reqClubActivityCondition.setLng(lng);
        PageObj<List<com.quanyan.club.entity.vo.resp.RespClubActivity>> pageObj =
                activityCRUDService.clubActivityListByCriteria(
                        reqClubActivityCondition, null);
        if(null == pageObj) {
            logger.warn("没有数据");
            return null;
        }
        List<com.quanyan.club.entity.vo.resp.RespClubActivity> list = pageObj.getItems();
        if(CollectionUtils.isEmpty(list)) {
            logger.warn("数据为空");
            return null;
        }
        List<RespSearchActivity> respSearchActivities = new ArrayList<RespSearchActivity>();
        for(com.quanyan.club.entity.vo.resp.RespClubActivity respClubActivity : list) {
            RespSearchActivity respSearchActivity =
                    activitySupportService.convertRespClubActivityToSearch(respClubActivity);
            if(null == respSearchActivity) {
                continue;
            }
            respSearchActivities.add(respSearchActivity);
        }
        long end = System.currentTimeMillis();
        logger.warn("-----计算时间-------------" + (end - start) + "------------------");
        logger.warn("返回：" + JSONObject.toJSONString(respSearchActivities));
        return respSearchActivities;
    }

    public APIResponse<PageObj<List<RespSearchActivity>>> queryPlaceActivityBySolr(
            double lat,double lng,double distance,int categoryId,int pageSize) {
        long start = System.currentTimeMillis();
        ReqClubActivitySearch reqActivitySearch = new ReqClubActivitySearch();
        reqActivitySearch.setLat(lat);
        reqActivitySearch.setLng(lng);
        reqActivitySearch.setCategoryId(categoryId);
        reqActivitySearch.setPageNum(0);
        reqActivitySearch.setPageSize(pageSize);
        reqActivitySearch.setDistance(distance);
        reqActivitySearch.setSortId(SearchConstants.ACTIVITY_TASK_SORT_DESC);
        APIResponse<PageObj<List<RespSearchActivity>>> resp =
                clubActivityService.queryActivityListByCondition(reqActivitySearch);
        PageObj<List<RespSearchActivity>> pageObj = resp.getData();
        if(null == pageObj) {
            return resp;
        }
        List<RespSearchActivity> list = pageObj.getItems();
        if(CollectionUtils.isEmpty(list)) {
            return resp;
        }
        for(RespSearchActivity respSearchActivity : list) {
            TbActivityDescExample example = new TbActivityDescExample();
            example.createCriteria().
                    andActivityIdEqualTo(Integer.parseInt(respSearchActivity.getActivityId()));
            List<TbActivityDesc> activityDescs =
                    tbActivityDescMapper.selectByExample(example);
            if(CollectionUtils.isEmpty(activityDescs)) {
                return resp;
            }
            TbActivityDesc tbActivityDesc = activityDescs.get(0);
            respSearchActivity.setActivityDetail(tbActivityDesc.getBodyDesc());
        }
        long end = System.currentTimeMillis();
        logger.warn("-----计算时间-------------" + (end - start) + "------------------");
        return resp;
    }


    public Map<Integer, List<RespPlaceClubInfo>> selectClubByPlaceIds(
            List<Integer> placeIds, int pageNum, int pageSize, int categoryId) {
        long start = System.currentTimeMillis();
        logger.warn("selectClubByPlaceIds入参：" + JSONObject.toJSONString(placeIds) + "," + categoryId);
        Map<Integer, List<RespPlaceClubInfo>> map =
                new HashMap<Integer, List<RespPlaceClubInfo>>();
        for(int placeId : placeIds) {
            List<RespPlaceClubInfo> placeClubInfos =
                    selectClubByPlaceId(placeId, pageNum, pageSize, categoryId);
            map.put(placeId, placeClubInfos);
        }
        long end = System.currentTimeMillis();
        logger.warn("-----计算时间-------------" + (end - start) + "------------------");
        logger.warn("返回：" + JSONObject.toJSONString(map));
        return map;
    }

    public Map<Integer,List<RespPlaceClubInfo>> selectActivityByPlaceIds(List<Integer> placeIds,
                                                                   int pageNum, int pageSize, int categoryId) {
        logger.warn("selectActivityByPlaceIds入参：" + JSONObject.toJSONString(placeIds) + "," + categoryId);
        long start = System.currentTimeMillis();
        Map<Integer,List<RespPlaceClubInfo>> map =
                new HashMap<Integer,List<RespPlaceClubInfo>>();
        for(int placeId : placeIds) {
            List<RespPlaceClubInfo> placeClubInfos =
                    selectActivityByPlaceId(placeId, pageNum, pageSize, categoryId);
            map.put(placeId, placeClubInfos);
        }
        long end = System.currentTimeMillis();
        logger.warn("返回：" + JSONObject.toJSONString(map));
        logger.warn("-----计算时间-------------" + (end - start) + "------------------");
        return map;
    }

    private List<RespPlaceClubInfo> selectClubByPlaceId(int placeId,
                                                  int pageNum, int pageSize, int categoryId) {
        List<RespPlaceClubInfo> resp = new ArrayList<RespPlaceClubInfo>();
                TbClubExample clubExample = new TbClubExample();
        TbClubExample.Criteria criteria = clubExample.createCriteria()
                .andPlaceBindIdEqualTo(placeId)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO).andStatusEqualTo(Constants.BYTE_ZERO);
        if(categoryId > 0) {
            criteria.andClubTypeEqualTo(categoryId);
        }
        int clubCount = tbClubMapper.countByExample(clubExample);
        if(clubCount == 0) {
            return null;
        }
        clubExample.setLimit(Limit.buildLimit(pageNum, pageSize));
        clubExample.setOrderByClause(" club_integr desc ");
        List<TbClub> clubs = tbClubMapper.selectByExample(clubExample);
        if(CollectionUtils.isEmpty(clubs)) {
            return null;
        }
        for(TbClub club : clubs) {
            RespPlaceClubInfo clubInfo = new RespPlaceClubInfo();
            clubInfo.setClubCount(clubCount);
            clubInfo.setActivityWeeks(clubSearchBizService.getActivityWeekDays(club.getId()));
            clubInfo.setClubName(club.getClubName());
            clubInfo.setRealNameAuth(clubHomePageService.isRealNameAuthClub(club.getId()));
            TbClubIntegralRule tbClubIntegralRule =
                    tbClubIntegralRuleMapper.selectByPrimaryKey(ClubConstants.GATHER_CLUB_DETAIL);//积分规则

            String defaultDetail = tbClubIntegralRule == null ? "世间竟有如此清新好玩的组织"
                    : tbClubIntegralRule.getFinishGrade();
            logger.warn("defaultDetail" + defaultDetail);
            if(StringUtils.isBlankOrNull(club.getPurpose())) {
                clubInfo.setClubDetail(defaultDetail);
            } else {
                clubInfo.setClubDetail(club.getPurpose());
            }

            clubInfo.setClubLogo(club.getLogoUrl());
            clubInfo.setClubId(club.getId());
            Integer memberCount = clubMemberService.countClubMembers(club.getId(), true);
            clubInfo.setClubMemberCount(memberCount);
            resp.add(clubInfo);
        }
        return resp;
    }

    private List<RespPlaceClubInfo> selectActivityByPlaceId(int placeId,
                                                      int pageNum, int pageSize, int categoryId) {
        List<RespPlaceClubInfo> resp = new ArrayList<RespPlaceClubInfo>();

        int count = clubActivityMapper.countPlaceActivity(placeId, categoryId);
        if(0 == count) {
            return null;
        }
        Limit limit = Limit.buildLimit(pageNum, pageSize);
        List<Integer> activityIds =
                clubActivityMapper.selectPlaceActivity(placeId,
                        limit.getStart(), limit.getSize(), categoryId);
        if(CollectionUtils.isEmpty(activityIds)) {
            return null;
        }
        for(Integer activityId : activityIds) {
            if(null == activityId || activityId == 0) {
                continue;
            }
            RespPlaceClubInfo clubInfo = new RespPlaceClubInfo();
            TbActivity tbActivity = tbActivityMapper.selectByPrimaryKey(activityId);
            TbActivityDescExample descExample = new TbActivityDescExample();
            descExample.createCriteria().andActivityIdEqualTo(activityId);
            List<TbActivityDesc> activityDescs =
                    tbActivityDescMapper.selectByExample(descExample);
            TbActivityDesc activityDesc = activityDescs.get(0);
            TbClubActivityExample clubActivityExample = new TbClubActivityExample();
            clubActivityExample.createCriteria().andActivityIdEqualTo(activityId);
            List<TbClubActivity> tbClubActivities =
                    tbClubActivityMapper.selectByExample(clubActivityExample);
            TbClubActivity clubActivity = tbClubActivities.get(0);
            clubInfo.setActivityDetail(activityDesc.getBodyDesc());
            clubInfo.setActivityName(tbActivity.getName());
            clubInfo.setLowestPrice(ActivityUtils.getLowestPrice(clubActivity));
            clubInfo.setStartTime(tbActivity.getStartTime());
            clubInfo.setActivityCount(count);
            clubInfo.setActivityId(activityId);
            resp.add(clubInfo);
        }
        return resp;
    }


    public RespMyLastActivity getMyLastActivity(int uid) {
        long start = System.currentTimeMillis();
        Integer activityId = clubActivityCRUDMapper.selectMyLastActivity(uid);
        if(null == activityId || activityId <= 0) {
            return null;
        }
        RespMyLastActivity respMyLastActivity = new RespMyLastActivity();
        com.quanyan.club.entity.vo.resp.RespClubActivity respClubActivity =
                activityCRUDService.selectClubActivityById(activityId);
        if(null == respClubActivity) {
            return null;
        }
        respMyLastActivity.setActivityId(respClubActivity.getActivityId());
        if(respClubActivity.getPlaceId() == 0) {
            respMyLastActivity.setActivitySite(respClubActivity.getPlaceAddress());
        } else {
            PlaceDubboProvider placeDubboProvider =
                    respClubActivity.getPlaceDubboProvider();
            respMyLastActivity.setActivitySite(placeDubboProvider.getName());
        }
        respMyLastActivity.setCategoryId(respClubActivity.getCategoryId());
        respMyLastActivity.setEndTime(respClubActivity.getEndTime());
        respMyLastActivity.setStartTime(respClubActivity.getStartTime());
        respMyLastActivity.setCurTime(respClubActivity.getCurTime());
        respMyLastActivity.setCategoryName(respClubActivity.getCategoryName());
        long end = System.currentTimeMillis();
        logger.warn("-----计算时间-------------" + (end - start) + "------------------");
        return respMyLastActivity;
    }

    public RespMyLastActivity getMyClubActivity(int uid) {
        logger.warn("getMyClubActivity入参：" + uid);
        long start = System.currentTimeMillis();
        ReqClubActivityCondition condition = new ReqClubActivityCondition();
        condition.setStatus(5);
        condition.setPageNum(0);
        condition.setPageSize(1);
        PageObj<List<com.quanyan.club.entity.vo.resp.RespClubActivity>> pageObj =
                activityCRUDService.clubActivityListByCriteria(condition, uid);
        if(null == pageObj) {
            return null;
        }
        if(CollectionUtils.isEmpty(pageObj.getItems())) {
            return null;
        }
        List<com.quanyan.club.entity.vo.resp.RespClubActivity> list = pageObj.getItems();
        com.quanyan.club.entity.vo.resp.RespClubActivity respClubActivity = list.get(0);
        RespMyLastActivity respMyLastActivity = new RespMyLastActivity();
        respMyLastActivity.setActivityId(respClubActivity.getActivityId());
        if(respClubActivity.getPlaceId() == 0) {
            respMyLastActivity.setActivitySite(respClubActivity.getPlaceAddress());
        } else {
            PlaceDubboProvider placeDubboProvider =
                    respClubActivity.getPlaceDubboProvider();
            respMyLastActivity.setActivitySite(placeDubboProvider.getName());
        }
        respMyLastActivity.setCategoryId(respClubActivity.getCategoryId());
        respMyLastActivity.setEndTime(respClubActivity.getEndTime());
        respMyLastActivity.setClubName(respClubActivity.getClubName());
        respMyLastActivity.setStartTime(respClubActivity.getStartTime());
        respMyLastActivity.setCurTime(respClubActivity.getCurTime());
        respMyLastActivity.setCategoryName(respClubActivity.getCategoryName());
        respMyLastActivity.setActivityCount(pageObj.getTotal());
        logger.warn("返回：" + JSONObject.toJSONString(respMyLastActivity));
        long end = System.currentTimeMillis();
        logger.warn("-----计算时间-------------" + (end - start) + "------------------");
        return respMyLastActivity;
    }

    /**
     * 判断用户是否为某俱乐部成员
     * @param clubId
     * @param uid
     * @return
     */
    @Override
    public RespIsClubMember isClubMember(int clubId, int uid) {

        RespIsClubMember result = new RespIsClubMember();

        //标志该用户是否为俱乐部成员，如果为false则不是该俱乐部成员，如果为true，则是该俱乐部成员。
        boolean flag = false;

        TbClubMember clubMember = this.getClubMember(clubId,uid);

        if(clubMember != null){
            flag = true;
            result.setRoleCode(clubMember.getRoleCode());
            result.setRoleName(clubMember.getRoleName());
        }

        result.setFlag(flag);

        return result;
    }

    @Override
    public APIResponse<PageObj<List<RespSearchActivity>>> queryActivityListByCondition(Integer uid, double lat, double lng, int pageNum, int pageSize)
    {
        //APP3.0需求精选活动
        ReqClubActivitySearch reqClubActivitySearch = new ReqClubActivitySearch();
        reqClubActivitySearch.setPageNum(pageNum);
        reqClubActivitySearch.setPageSize(pageSize);
        List<Integer> clubCategories = new ArrayList<Integer>();
        if(null != uid && uid != 0)
        {
            clubCategories = clubOpenExtendMapper.getMyJoinClubCategoryList(uid);
            logger.warn("相关的俱乐部类型有:{}", clubCategories);
            List<Integer> uids = new ArrayList<Integer>();
            uids.add(uid);
            Map<Integer, List<RespOpenUserInterest>> map =
                    userServiceFacade.batchQueryUserInterest(uids);
            if(map.containsKey(uid))
            {
                List<RespOpenUserInterest> interests = map.get(uid);
                if(null != interests && interests.size() > 0)
                {
                    logger.warn("感兴趣的运动类型有:{}", interests);
                    for(RespOpenUserInterest interest : interests)
                    {
                        clubCategories.add(interest.getCategoryId());
                    }

                }
            }
            if(null != clubCategories && clubCategories.size() > 0)
            {
                HashSet<Integer> hs = new HashSet<Integer>(clubCategories);
                logger.warn("hs:",hs);
                reqClubActivitySearch.setCategories(new ArrayList<Integer>(hs));
                logger.warn("req:"+ JSON.toJSONString(reqClubActivitySearch));
            }
        }
        reqClubActivitySearch.setLat(lat);
        reqClubActivitySearch.setLng(lng);
        APIResponse<PageObj<List<RespSearchActivity>>> res = clubActivityService.queryActivityListByCondition(reqClubActivitySearch);
        return res;
    }

    public PageObj<List<RespClubActivity>> latestActivityList4Place(Integer placeId, Integer pageNum, Integer pageSize) {
        //获取活动通用详情信息 调用通用接口
        PageObj<List<ActivityInfo>> pageObj = activityOpenService.queryOneActivityByPlaceId(placeId, pageNum + 1, pageSize);
        List<ActivityInfo> activityList = pageObj.getItems();
        if (CollectionUtils.isEmpty(activityList)) {
            return null;
        }
        List<Integer> activityIdList = new ArrayList<>();
        for (ActivityInfo activityInfo : activityList) {
            activityIdList.add(activityInfo.getId());
        }
        List<RespClubActivity> respClubActivityList = batchQueryActivityList(activityIdList, activityList);
        return PageObj.create(pageObj.getTotal(), pageNum + 1, pageSize, respClubActivityList);
    }

    @Override
    public boolean isSportClubMember(int uid, int sportTypeId) {
        List<RespClubBaseInfo> myClubs = getMyClubs(uid);
        for (RespClubBaseInfo clubBaseInfo : myClubs){
            if (clubBaseInfo.getClubType() == sportTypeId){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isSportClubAdmin(int uid, int sportTypeId) {
        List<RespClubBaseInfo> myClubs = getMyClubs(uid);
        List<Integer> clubIds = new ArrayList<>();
        for (RespClubBaseInfo clubBaseInfo : myClubs){
            if (clubBaseInfo.getClubType() == sportTypeId){
                clubIds.add(clubBaseInfo.getClubId());
            }
        }
        if (clubIds.isEmpty()){
            return false;
        }
         return isClubAdmin(uid, clubIds);
    }

    @Override
    public List<RespClubBaseInfo> getSportClubsOfAdmin(int uid, int sportTypeId) {
        List<RespClubBaseInfo> myClubs = getMyClubs(uid);
        List<RespClubBaseInfo> clubs = new ArrayList<>();
        for (RespClubBaseInfo clubBaseInfo : myClubs){
            if (clubBaseInfo.getClubType() == sportTypeId
                    && isClubAdmin(uid, Arrays.asList(clubBaseInfo.getClubId()))){
                clubs.add(clubBaseInfo);
            }
        }
        return clubs;
    }

    @Override
    public List<Integer> getSportClubIdsOfAdmin(int uid, int sportTypeId) {
        List<RespClubBaseInfo> myClubs = getMyClubs(uid);
        List<Integer> clubIds = new ArrayList<>();
        for (RespClubBaseInfo clubBaseInfo : myClubs){
            if (clubBaseInfo.getClubType() == sportTypeId){
                clubIds.add(clubBaseInfo.getClubId());
            }
        }
        Iterator<Integer> ite = clubIds.iterator();
        while (ite.hasNext()){
            if (!isClubAdmin(uid, Arrays.asList(ite.next()))){
                ite.remove();
            }
        }
        return clubIds;
    }

    private boolean isClubAdmin(int uid, List<Integer> clubIds){
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andUidEqualTo(uid)
                .andRoleCodeIn(Arrays.asList(Constants.ClubRole.CLUB_ROLE_PRESIDENT,
                        Constants.ClubRole.ROLE_CLUB_ADMIN,
                        Constants.ClubRole.ROLE_CLUB_FINANCIAL))
                .andClubIdIn(clubIds)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        int count = clubMemberMapper.countByExample(example);
        return count > 0;
    }

    private List<RespClubBaseInfo> getMyClubs(int uid) {
        ReqClubPage reqClubPage = new ReqClubPage();
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        reqClubPage.setParamMap(map);
        List<RespClubBaseInfo> myCreateClubs = clubService.listMyCreateClubs(uid, reqClubPage);
        map.clear();
        map.put("type", 2);
        reqClubPage.setParamMap(map);
        List<RespClubBaseInfo> myJoinedClubs = clubService.listMyJoinedClubs(uid, reqClubPage);
        List<RespClubBaseInfo> myClubs = new ArrayList<>();
        myClubs.addAll(myCreateClubs);
        myClubs.addAll(myJoinedClubs);
        return myClubs;
    }

    /**
     * 获取俱乐部成员列表
     * @param clubId        俱乐部ID
     * @param isTeamMember  是否只获取俱乐部代表队成员
     * @return
     */
    @Override
    public List<RespClubMemberBaseInfo> getClubMembers(int clubId, boolean isTeamMember) {
        TbClubMemberExample example = new TbClubMemberExample();
        TbClubMemberExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if (isTeamMember){
            criteria.andIsTeamMemberEqualTo(Constants.YES);
        }
        List<TbClubMember> members = clubMemberMapper.selectByExample(example);
        List<RespClubMemberBaseInfo> respClubMemberBaseInfos = new ArrayList<>();
        for (TbClubMember member : members){
            RespClubMemberBaseInfo respClubMemberBaseInfo = new RespClubMemberBaseInfo();
            respClubMemberBaseInfo.setClubId(member.getClubId());
            respClubMemberBaseInfo.setUid(member.getUid());
            respClubMemberBaseInfos.add(respClubMemberBaseInfo);
        }
        return respClubMemberBaseInfos;
    }

    /**
     * 获取俱乐部的主席和普通管理员（不包含财务管理员）
     * @param clubId
     * @return
     */
    @Override
    public List<RespClubMemberBaseInfo> getClubAdmins(int clubId){
        TbClubMemberExample example = new TbClubMemberExample();
        TbClubMemberExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(clubId)
                .andRoleCodeIn(Arrays.asList(Constants.ClubRole.CLUB_ROLE_PRESIDENT,
                        Constants.ClubRole.ROLE_CLUB_FINANCIAL,
                        Constants.ClubRole.ROLE_CLUB_ADMIN))
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> members = clubMemberMapper.selectByExample(example);
        List<RespClubMemberBaseInfo> list = new ArrayList<>();
        for (TbClubMember member : members){
            RespClubMemberBaseInfo memberBaseInfo = new RespClubMemberBaseInfo();
            memberBaseInfo.setUid(member.getUid());
            memberBaseInfo.setClubId(member.getClubId());
            list.add(memberBaseInfo);
        }
        return list;
    }

    /**
     * 判断该成员在俱乐部中是否存在未读通告
     * @param clubId
     * @param uid
     * @return true 为存在，false 为不存在
     */
    @Override
    public boolean isHaveNotReadAnnouncement(int clubId, int uid) {
        //已读公告个数
        TbClubAnnouncementUidRelationExample example = new TbClubAnnouncementUidRelationExample();
        example.createCriteria().andClubIdEqualTo(clubId).andUidEqualTo(uid);
        Integer clubAnnouncementUidRelationCount = this.clubAnnouncementUidRelationMapper.countByExample(example);

        //俱乐部发布的公告的个数
        TbClubAnnouncementExample announcementExample = new TbClubAnnouncementExample();
        announcementExample.createCriteria().andIsDeleteEqualTo(0).andClubIdEqualTo(clubId);
        Integer clubAnnouncementCount = this.clubAnnouncementMapper.countByExample(announcementExample);
        if (clubAnnouncementCount.intValue() > clubAnnouncementUidRelationCount) {
            return true;
        }else{
            return false;
        }
    }


    /**
     * 获取俱乐部常驻球馆信息
     * @param clubId
     * @return
     */
    @Override
    public RespClubResidentPlace getClubResidentPlace(int clubId) {
        TbClub club = this.clubMapper.selectByPrimaryKey(clubId);
        if(null == club){
            return null;
        }else{
            RespClubResidentPlace place = new RespClubResidentPlace();
            place.setResidentPlaceId(club.getResidentPlaceId());
            place.setResidentPlaceName(club.getResidentPlaceName());
            return place;
        }
    }

    /**
     * 获取用户所属俱乐部信息
     * @param uid
     * @return
     */
    @Override
    public List<RespClubOpenInfo> getUserClubInfoList(int uid) {
        Map map = new HashMap();
        map.put("uid",uid);
        List<RespClubOpenInfo> list = this.clubOpenExtendMapper.listClubOpenInfo(map);
        return list;
    }

    /**
     * 获取俱乐部成员
     * @param clubId
     * @param uid
     * @return
     */
    private TbClubMember getClubMember(int clubId, int uid){
        TbClubMemberExample example = new TbClubMemberExample();
        TbClubMemberExample.Criteria criteria = example.createCriteria();

        criteria.andIsDeleteEqualTo((byte)0);
        criteria.andClubIdEqualTo(clubId);
        criteria.andUidEqualTo(uid);

        List<TbClubMember> clubMemberList = this.clubMemberMapper.selectByExample(example);

        TbClubMember clubMember;

        if (clubMemberList.isEmpty()) {
            clubMember = null;
        } else {
            clubMember = clubMemberList.get(0);
        }
        return clubMember;
    }

    /**
     * 获取已读通告最新的一条
     * @param clubId
     * @param uid
     * @return
     */
    private TbClubAnnouncementUidRelation getTheLastReadAnnouncement(int clubId,int uid){
        TbClubAnnouncementUidRelationExample example = new TbClubAnnouncementUidRelationExample();
        TbClubAnnouncementUidRelationExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(clubId);
        criteria.andUidEqualTo(uid);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        example.setOrderByClause("create_time desc limit 0,1");
        List<TbClubAnnouncementUidRelation> clubAnnouncementUidRelationList = this.clubAnnouncementUidRelationMapper.selectByExample(example);
        if(clubAnnouncementUidRelationList.isEmpty()){
            return null;
        }else{
            return clubAnnouncementUidRelationList.get(0);
        }
    }

    /**
     * 获取俱乐部通告列表
     * @param clubId
     * @param createTime
     * @return
     */
    private List<TbClubAnnouncement> getClubAnnouncementList(int clubId,Date createTime){
        TbClubAnnouncementExample example = new TbClubAnnouncementExample();
        TbClubAnnouncementExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(clubId);
        if(null != createTime){
            criteria.andCreateTimeGreaterThanOrEqualTo(createTime);
        }
        criteria.andIsDeleteEqualTo((int) Constants.IS_DELETE_FALSE);
        List<TbClubAnnouncement> clubAnnouncementList = this.clubAnnouncementMapper.selectByExample(example);

        return clubAnnouncementList;
    }

    /**
     * 获取俱乐部成员在俱乐部中的线上线下资金
     * @param uid           俱乐部成员uid
     * @param clubId        俱乐部id
     * @return
     */
    @Override
    public RespClubMemberFund getClubMemberFund(int uid, int clubId) {
        RespClubMemberFund fund = new RespClubMemberFund();
        BigDecimal total = BigDecimal.ZERO;
        TbClubOfflineMemberAccount offlineAccount = clubFinanceMgmService.getClubMemberOfflineAccount(uid, clubId);
        if (offlineAccount != null) {
            fund.setOfflineFund(offlineAccount.getMoneyTotal());
            total = total.add(offlineAccount.getMoneyTotal());
        }
        TbClubOnlineMemberAccount onlineAccount = clubFinanceMgmService.getClubMemberOnlineAccount(uid, clubId);
        if (offlineAccount != null){
            fund.setOnlineFund(onlineAccount.getMoneyTotal());
            total = total.add(onlineAccount.getMoneyTotal());
        }
        fund.setTotalFund(total);
        return fund;
    }

    /**
     * 获取pk俱乐部
     * @param cityId        城市id
     * @param sportType     俱乐部运动类型
     * @param pageNum       页码
     * @param pageSize      每页记录条数
     * @return
     */
    @Override
    public PageObj<List<RespClubBaseInfo>> getPKClubs(Integer cityId, Integer sportType, @NotNull Integer pageNum, @NotNull Integer pageSize) {
        //pageNum = pageNum +1;
        TbClubExample clubExample = new TbClubExample();
        TbClubExample.Criteria criteria = clubExample.createCriteria();
        if (cityId != null){
            criteria.andCityIdEqualTo(cityId);
        }
        if (sportType != null){
            criteria.andClubTypeEqualTo(sportType);
        }
        int total = clubMapper.countByExample(clubExample);
        Limit limit = Limit.buildLimit(pageNum+1, pageSize);
        clubExample.setLimit(limit);
        List<TbClub> tbClubs = clubMapper.selectByExample(clubExample);
        List<RespClubBaseInfo> list = new ArrayList<>();
        for (TbClub tbClub : tbClubs){
            RespClubBaseInfo clubBaseInfo = clubService.convert2RespClubBaseInfo(null, tbClub, false);
            int ranking = clubService.getClubRanking(tbClub.getId(), cityId);           //城市排名
            clubBaseInfo.setRanking(ranking);
            clubBaseInfo.setRankingNa(clubService.getClubRanking(tbClub.getId(), null)); //全国排名
            list.add(clubBaseInfo);
        }
        return PageObj.create(total, pageNum, pageSize, list);
    }

    /**
     *  根据俱乐部名称关键字搜索俱乐部
     * @param nameKeyword       俱乐部名称关键字
     * @return
     */
    @Override
    public PageObj<List<RespClubBaseInfo>> getClubByName(String nameKeyword, List<Integer> sportTypeIds, Integer cityId, Integer districtId,
                                                         @NotNull Integer pageNum, @NotNull Integer pageSize) {
        //pageNum = pageNum + 1;
        TbClubExample example = new TbClubExample();
        TbClubExample.Criteria criteria = example.createCriteria();
        if (!StringUtil.isBlankOrNull(nameKeyword)){
           criteria.andClubNameLike("%" + nameKeyword + "%");
        }
        if (sportTypeIds != null && sportTypeIds.size() != 0){
            criteria.andClubTypeIn(sportTypeIds);
        }
        if (cityId != null && cityId != 0){
            criteria.andCityIdEqualTo(cityId);
        }
        if (districtId != null && districtId != 0){
            criteria.andDistrictIdEqualTo(districtId);
        }
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        int total = clubMapper.countByExample(example);
        example.setLimit(Limit.buildLimit(pageNum+1, pageSize));
        List<TbClub> tbClubs = clubMapper.selectByExample(example);
        List<RespClubBaseInfo> clubBaseInfos = new ArrayList<>();
        for (TbClub tbClub : tbClubs){
            clubBaseInfos.add(clubService.convert2RespClubBaseInfo(null, tbClub, false));
        }
        return PageObj.create(total, pageNum, pageSize, clubBaseInfos);
    }

    /**
     * 俱乐部推荐
     * @param residentPlaceId   常驻球馆id
     * @param sportType         俱乐部类型id
     * @param pageNum           页码
     * @param pageSize          每页记录数
     * @return
     */
    @Override
    public PageObj<List<RespClubRecommendInfo>> getRecommendClubs(Integer residentPlaceId, Integer sportType,
                                                                  Integer pageNum, Integer pageSize) {
        //pageNum = pageNum + 1;
        TbClubExample example = new TbClubExample();
        TbClubExample.Criteria criteria = example.createCriteria();
        if (residentPlaceId != null && residentPlaceId != 0){
            criteria.andResidentPlaceIdEqualTo(residentPlaceId);
        }
        if (sportType != null && sportType != 0){
            criteria.andClubTypeEqualTo(sportType);
        }
        int total = clubMapper.countByExample(example);
        example.setLimit(Limit.buildLimit(pageNum+1, pageSize));
        example.setOrderByClause(" integral desc"); //积分倒序
        List<TbClub> clubs = clubMapper.selectByExample(example);
        List<RespClubRecommendInfo> clubBaseInfos = new ArrayList<>();
        for (TbClub club : clubs){
            RespClubRecommendInfo info = new RespClubRecommendInfo();
            info.setClubId(club.getId());
            info.setClubLogo(club.getLogoUrl());
            info.setClubName(club.getClubName());
            info.setLevel(club.getLevel());
            info.setIntegral(club.getIntegral());
            clubBaseInfos.add(info);
        }
        return PageObj.create(total, pageNum, pageSize, clubBaseInfos);
    }

    /**
     * 获取俱乐部简要信息列表
     * @param clubIds           俱乐部id列表
     * @return
     */
    @Override
    public Map<Integer, RespClubPlainInfo> getClubBaseInfoList(List<Integer> clubIds) {
        Map<Integer, RespClubPlainInfo> map = new HashMap<>();
        if (clubIds == null || clubIds.size()==0){
            return map;
        }
        TbClubExample example = new TbClubExample();
        example.createCriteria().andIdIn(clubIds).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClub> tbClubs = clubMapper.selectByExample(example);

        for (TbClub tbClub : tbClubs) {
            RespClubPlainInfo info = new RespClubPlainInfo();
            info.setCityId(tbClub.getCityId());
            info.setDistinctId(tbClub.getDistrictId());
            info.setClubId(tbClub.getId());
            info.setClubName(tbClub.getClubName());
            info.setLogo(tbClub.getLogoUrl());
            info.setIntegral(tbClub.getIntegral());
            info.setLevel(tbClub.getLevel());
            info.setIntroduce(tbClub.getIntroduce());
            map.put(tbClub.getId(), info);
        }
        return map;
    }

    /**
     * 根据用户id获取此用户创建的，加入的俱乐部基本信息
     * @param uid       用户id
     * @return
     */
    @Override
    public List<RespClubBaseInfo> getClubBaseInfoByUserId(Integer uid) {
        List<RespClubBaseInfo> clubBaseInfos = new ArrayList<>();
        TbClubMemberExample clubMemberExample = new TbClubMemberExample();
        clubMemberExample.createCriteria().andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> members = clubMemberMapper.selectByExample(clubMemberExample);
        List<Integer> clubIds = new ArrayList<>();
        for (TbClubMember clubMember : members){
            clubIds.add(clubMember.getClubId());
        }
        if (clubIds.isEmpty()){
            return clubBaseInfos;
        }
        TbClubExample clubExample = new TbClubExample();
        clubExample.createCriteria().andIdIn(clubIds).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClub> tbclubs = clubMapper.selectByExample(clubExample);
        for (TbClub tbClub : tbclubs){
            clubBaseInfos.add(clubService.convert2RespClubBaseInfo(uid, tbClub, false));
        }
        return clubBaseInfos;
    }

    /**
     * 批量获取俱乐部中是代表队的成员uid
     * @param clubIds           俱乐部id列表
     * @return
     */
    @Override
    public Map<Integer, List<Integer>> getClubsTeamMembersId(List<Integer> clubIds) {
        Map<Integer, List<Integer>> result = new HashMap<>();
        for (Integer clubId : clubIds){
            if (clubId == null){
                continue;
            }
            TbClubMemberExample example = new TbClubMemberExample();
            example.createCriteria()
                    .andClubIdEqualTo(clubId)
                    .andIsTeamMemberEqualTo(Constants.BYTE_ONE)
                    .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            List<TbClubMember> clubTeamMembers = clubMemberMapper.selectByExample(example);
            List<Integer> uids = new ArrayList<>();
            for (TbClubMember m : clubTeamMembers){
                uids.add(m.getUid());
            }
            result.put(clubId, uids);
        }
        return result;
    }

    /**
     * 根据uid，获取此用户在俱乐部中身份为代表队员/管理员/主席的俱乐部id
     * @param uid           用户id
     * @return
     */
    @Override
    public List<Integer> getClubIds(Integer uid) {
        List<Integer> clubIds = new ArrayList<>();
        if (uid == null){
            return clubIds;
        }
        TbClubMemberExample exmaple = new TbClubMemberExample();
        exmaple.createCriteria().andUidEqualTo(uid)
                .andIsTeamMemberEqualTo(Constants.BYTE_ONE)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> tmembers = clubMemberMapper.selectByExample(exmaple);
        for (TbClubMember m: tmembers){
            clubIds.add(m.getClubId()); //是代表队成员的
        }
        exmaple.clear();
        exmaple.createCriteria()
                .andUidEqualTo(uid)
                .andRoleCodeIn(Arrays.asList(Constants.ClubRole.CLUB_ROLE_PRESIDENT, Constants.ClubRole.ROLE_CLUB_ADMIN));
        List<TbClubMember> members = clubMemberMapper.selectByExample(exmaple);
        for (TbClubMember m: members){
            clubIds.add(m.getClubId()); //主席、管理员
        }
        List<Integer> listWithoutDup = new ArrayList<>(new HashSet<>(clubIds)); //去重，可能有成员既是代表队的也是主席/管理员
        return listWithoutDup;
    }

    /**
     * 获取我加入的某种运动类型的俱乐部
     * @param uid           用户id
     * @param sportTypeId   俱乐部运动类型id
     * @return
     */
    @Override
    public List<Integer> getClubIds(Integer uid, Integer sportTypeId) {
        List<RespClubBaseInfo> list = this.getClubBaseInfoByUserId(uid);
        List<Integer> clubIds = new ArrayList<>();
        for (RespClubBaseInfo baseInfo : list){
            if (baseInfo.getClubType().intValue() == sportTypeId){   //知道运动类型的
                clubIds.add(baseInfo.getClubId());
            }
        }
        return clubIds;
    }

    /**
     * 更新俱乐部线上账户资金
     * @param clubId            俱乐部id
     * @param tradeNo           交易号，订单号，活动编号
     * @param fee               金额
     * @param remark            备注
     * @param incr              true 充值，false 扣除
     * @return
     */
    @Override
    public APIResponse updateClubOnlineAccountBalance(Integer clubId, Integer activityId, String tradeNo,
                                                      BigDecimal fee, String remark, boolean incr) {
        return clubAccountService.updateClubOnlineAccountBalance(clubId, activityId, NumberGenerator.getNextOrderNo(), tradeNo, fee, remark, incr, 3);
    }

    @Override
    @Transactional
    public APIResponse settlementClubGameActivity(ReqClubSettlementInfo settlementInfo, List<ReqClubSettlementInfo> userSettlementInfos) {

        Integer clubId = settlementInfo.getClubId();
        Integer activityId = settlementInfo.getActivityId();
        BigDecimal payFee = settlementInfo.getPayFee();
        if (clubId == null || activityId == null || payFee.doubleValue() <=0){
            return APIResponse.returnFail("参数错误！");
        }
        TbClubActivitySettlementExample example = new TbClubActivitySettlementExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andActivityIdEqualTo(activityId);
        if (clubActivitySettlementMapper.countByExample(example) > 0){
            return APIResponse.returnFail("此活动的资金已经结算到俱乐部！");
        }

        TbClubActivitySettlement clubActivitySettlement = new TbClubActivitySettlement();
        clubActivitySettlement.setActivityId(activityId);
        clubActivitySettlement.setClubId(clubId);
        clubActivitySettlement.setType(2);      //俱乐部赛事活动结算
        clubActivitySettlement.setDealMoney(settlementInfo.getPayFee()); //应付金额
        clubActivitySettlement.setAccumulateMoney(settlementInfo.getEggDeductionFee());
        clubActivitySettlement.setIntegralMoney(settlementInfo.getIntegralDeductionFee());
        clubActivitySettlement.setPayMoney(settlementInfo.getRealPayFee());
        clubActivitySettlement.setRemark(settlementInfo.getRemark());
        int ret = clubActivitySettlementMapper.insertSelective(clubActivitySettlement);
        if (ret == 1) {
            for (ReqClubSettlementInfo userSettlementInfo: userSettlementInfos){
                TbClubActivitySettlementDetail detail = new TbClubActivitySettlementDetail();
                detail.setUid(settlementInfo.getUid());
                detail.setClubId(clubId);
                detail.setActivityId(activityId);
                detail.setDealMoney(settlementInfo.getPayFee()); //应付金额
                detail.setAccumulateMoney(settlementInfo.getEggDeductionFee());
                detail.setIntegralMoney(settlementInfo.getIntegralDeductionFee());
                detail.setPayMoney(settlementInfo.getRealPayFee());
                detail.setRemark(settlementInfo.getRemark());
                detail.setType(2);      //俱乐部赛事
                clubActivitySettlementDetailMapper.insertSelective(detail);
            }
        }
        return APIResponse.returnSuccess("结算成功！");
    }

    /**
     * 更新俱乐部成员线上账户资金
     * @param  clubId        俱乐部id
     * @param  uid       俱乐部成员用户id
     * @param  fee           金额
     * @param  incr         是否添加 true为增加 false为扣除
     * @return
     */
    @Override
    public APIResponse updateClubMemmberOnlineAccountBalance(Integer clubId, Integer uid, BigDecimal fee, boolean incr) {
        Object obj = clubAccountService.addOrDeductionPersonClubAccountBalance(fee, uid, clubId, incr);
        if (obj == null){
            return APIResponse.returnFail("更新俱乐部成员线上资金失败");
        }
        return APIResponse.returnSuccess();
    }

    public RespLatesActivityInfo latestActivityInfo(Integer placeId,Integer uid, Integer categoryId) {
        //获取活动通用详情信息 调用通用接口
        PageObj<List<ActivityInfo>> pageObj = activityOpenService.queryOneActivityByPlaceId(placeId,categoryId,0,1);
        if (CollectionUtils.isEmpty(pageObj.getItems())) {
            return null;
        }
        List<ActivityInfo> activityInfoList = pageObj.getItems();
        RespLatesActivityInfo respLatesActivityInfo = new RespLatesActivityInfo();
        respLatesActivityInfo.setActivityCount(pageObj.getTotal());

        //分流
        ActivityInfo activityInfo = null;
        Integer activityId = null;
        //获取时间离现在最近的活动
        List<Integer> idList = clubActivityMapper.selectActivityByUid(uid, categoryId);
        if(null != idList && idList.size() > 0)
        {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("isNotStart", 1L);
            map.put("placeId", placeId);
            ActivityInfo info = activityOpenService.selectSignActivityByUid(idList, map);

            if(null != info)
            {
                activityInfo = info;
                respLatesActivityInfo.setActivityId(activityInfo.getId());
                respLatesActivityInfo.setActivityTitle(activityInfo.getName());
                respLatesActivityInfo.setActivityDate(activityInfo.getStartTime());
                respLatesActivityInfo.setGroupId(activityInfo.getGroupId());
                Integer userId = clubActivityMapper.selectUidByActivityId(activityInfo.getId());
                respLatesActivityInfo.setUid(userId);
                respLatesActivityInfo.setAllReadySignUp(Constants.BYTE_ONE);
                return respLatesActivityInfo;
            }
        }
        activityInfo = activityInfoList.get(0);
        respLatesActivityInfo.setActivityId(activityInfo.getId());
        respLatesActivityInfo.setActivityTitle(activityInfo.getName());
        respLatesActivityInfo.setActivityDate(activityInfo.getStartTime());
        respLatesActivityInfo.setGroupId(activityInfo.getGroupId());
        Integer userId = clubActivityMapper.selectUidByActivityId(activityInfo.getId());
        respLatesActivityInfo.setUid(userId);
        /*Map<Integer ,Integer> userIdMap = new HashMap();
        List<RespUserInfoBase> userInfoBaseList = activityMemberList(activityInfo.getId());//显示活动成员数量
        Byte flag = 0;
        if(CollectionUtils.isNotEmpty(userInfoBaseList)){
            for(RespUserInfoBase userInfoBase : userInfoBaseList){
                userIdMap.put(userInfoBase.getUid(),userInfoBase.getUid());
            }
            // 判断当前用户是否参加该活动
            if(userIdMap.containsKey(uid)){
                flag = 1;
            }
        }*/
        respLatesActivityInfo.setAllReadySignUp(Constants.BYTE_ZERO);
        return respLatesActivityInfo;
    }

    public List<RespClubActivity> batchQueryActivityList(List<Integer> activityIdList, List<ActivityInfo> activityInfoList) {
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andActivityIdIn(activityIdList);
        List<TbClubActivity> tbClubActivityList = tbClubActivityMapper.selectByExample(example);
        //组合活动对象(主体+扩展)
        List<Integer> placeIds = new ArrayList<>();
        List<RespClubActivity> respClubActivityList = new ArrayList<>();
        for(ActivityInfo activityInfo : activityInfoList)
        {
            if(activityInfo.getPlaceId() != 0)
            {
                placeIds.add(activityInfo.getPlaceId());
            }
        }
        Map<Integer, PlaceDubboProvider> placeMap = getPlaceMap(placeIds);
        getPropertiesToClubActivitys(tbClubActivityList,activityInfoList,placeMap,respClubActivityList);
        return respClubActivityList;
    }

    public List<RespClubActivity> batchQueryActivityList(List<Integer> activityIdList) {
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andActivityIdIn(activityIdList);
        List<TbClubActivity> tbClubActivityList = tbClubActivityMapper.selectByExample(example);
        List<ActivityInfo> activityInfoList = activityOpenService.queryActivityList(activityIdList);
        //组合活动对象(主体+扩展)

        List<Integer> placeIds = new ArrayList<>();
        for(ActivityInfo activityInfo : activityInfoList)
        {
            if(activityInfo.getPlaceId() != 0)
            {
                placeIds.add(activityInfo.getPlaceId());
            }
        }
        Map<Integer, PlaceDubboProvider> placeMap = getPlaceMap(placeIds);
        List<RespClubActivity> respClubActivityList = new ArrayList<>();
        getPropertiesToClubActivitys(tbClubActivityList,activityInfoList,placeMap,respClubActivityList);
        return respClubActivityList;
    }

    private Map<Integer, PlaceDubboProvider> getPlaceMap(List<Integer> placeIdList)
    {
        //调场馆模块的接口 场馆
        Map<Integer, PlaceDubboProvider> map = placeClient.getPlaceListByPlaceId(placeIdList);
        return map;
    }

    public void getPropertiesToClubActivitys(List<TbClubActivity> tbClubActivityList,
                                             List<ActivityInfo> activityList,
                                             Map<Integer, PlaceDubboProvider> placeMap,
                                             List<RespClubActivity> respClubActivityList)
    {
        for (TbClubActivity tbClubActivity : tbClubActivityList) {
            RespClubActivity respClubActivity = null;
            //俱乐部信息
            TbClub tbClub = tbClubMapper.selectByPrimaryKey(tbClubActivity.getClubId());
            for (ActivityInfo activityInfo : activityList) {
                respClubActivity = new RespClubActivity();
                if (tbClubActivity.getActivityId().equals(activityInfo.getId())) {
                    copyToRespClubActivity(respClubActivity, tbClubActivity, activityInfo, tbClub);
                    if(null != activityInfo.getPlaceId() &&
                            activityInfo.getPlaceId() != 0 && null != placeMap)
                    {
                        PlaceDubboProvider placeDubboProvider = new PlaceDubboProvider();
                        BeanCopierUtils.copyProperties(placeMap.get(activityInfo.getPlaceId()), placeDubboProvider);
                        respClubActivity.setPlaceDubboProvider(placeDubboProvider);
                    }
                    respClubActivityList.add(respClubActivity);
                }
            }
        }
        if(null != placeMap)
        {
            placeMap.clear();
        }
    }

    /**
     * 给返回协议对象赋值(简要)
     */
    public void copyToRespClubActivity(RespClubActivity respClubActivity,
                                       TbClubActivity tbClubActivity,
                                       ActivityInfo activityInfo, TbClub tbClub) {
        //活动海报
        RespActivityPoster respActivityPoster = new RespActivityPoster();
        Integer posterPicId = 0;
        if (activityInfo != null) {
            posterPicId = activityInfo.getPosterPicId();
        }
        TbActivityPoster tbActivityPoster;
        if (null != posterPicId) {
            tbActivityPoster = tbActivityPosterMapper.selectByPrimaryKey(posterPicId);
            if (null != tbActivityPoster) {
                BeanCopierUtils.copyProperties(tbActivityPoster, respActivityPoster);
            }
        }
        if (null != activityInfo) {
            BeanCopierUtils.copyProperties(activityInfo, respClubActivity);
        }

        if (null != tbClubActivity) {
            BeanCopierUtils.copyProperties(tbClubActivity, respClubActivity);
            respClubActivity.setFemaleMemberFee(tbClubActivity.getFemaleMemberFee());
            respClubActivity.setIsSame(ActivityUtils.isSamePrice(tbClubActivity));
            respClubActivity.setPrice(ActivityUtils.getLowestPrice(tbClubActivity));
        }
        if (null != tbClub) {
            respClubActivity.setClubId(tbClub.getId());
            respClubActivity.setClubName(tbClub.getClubName());
            respClubActivity.setLogoUrl(tbClub.getLogoUrl());
        }
        respClubActivity.setIsSettle(tbClubActivity.getIsSettle().intValue());
        respClubActivity.setCurTime(new Date());
        respClubActivity.setId(respClubActivity.getActivityId());
        respClubActivity.setRespActivityPoster(respActivityPoster);
        if (activityInfo != null && null == activityInfo.getPlaceId()
                && null == activityInfo.getPlaceAddress()) {
            return;
        }

    }

    /**
     * 我管理的俱乐部列表信息
     * @param uid
     * @return
     */
    @Override
    public List<RespClubOpenInfo> getMyManageClubList(int uid) {


        Map map = new HashMap();
        map.put("uid",uid);
        List<RespClubOpenInfo> myManageClubList = this.clubOpenExtendMapper.getMyManageClubList(map);
        if (!myManageClubList.isEmpty()) {
            for (RespClubOpenInfo respClubOpenInfo : myManageClubList) {
                if (respClubOpenInfo!=null) {
                    APIResponse<RespUserInfoBase> apiResponse = this.userServiceFacade.queryUserInfo(respClubOpenInfo.getUid());
                    if (apiResponse.isRet()) {
                        respClubOpenInfo.setPresidentName(apiResponse.getData().getNickName());
                    }else{
                        respClubOpenInfo.setPresidentName("");
                    }
                    respClubOpenInfo.setMemberCount(this.clubMemberService.countClubMembers(respClubOpenInfo.getClubId(), true));

                }

            }
        }
        return myManageClubList;
    }

    public List<RespClubPlainInfo> getMyManageClubs(int uid) {
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andUidEqualTo(uid)
                .andRoleCodeIn(Arrays.asList(
                        Constants.ClubRole.CLUB_ROLE_PRESIDENT,
                        Constants.ClubRole.ROLE_CLUB_ADMIN,
                        Constants.ClubRole.ROLE_CLUB_FINANCIAL))
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubMember> tbClubMembers = clubMemberMapper.selectByExample(example);
        List<RespClubPlainInfo> resultList = new ArrayList<>();
        for (TbClubMember clubMember : tbClubMembers){

            TbClub tbClub = clubMapper.selectByPrimaryKey(clubMember.getClubId());
            if (tbClub == null){
                continue;
            }
            RespClubPlainInfo plainInfo = new RespClubPlainInfo();
            plainInfo.setClubId(tbClub.getId());
            int typeId = tbClub.getClubType();
            if(typeId <= 4) {
                plainInfo.setClubTypeId(typeId);
            }
            plainInfo.setClubName(tbClub.getClubName());
            plainInfo.setLogo(tbClub.getLogoUrl());
            plainInfo.setIntroduce(tbClub.getIntroduce());
            plainInfo.setLevel(tbClub.getLevel());
            plainInfo.setIntegral(tbClub.getIntegral());

            resultList.add(plainInfo);
        }

        return resultList;
    }

    /**
     * 我加入的俱乐部列表信息
     * @param uid
     * @return
     */
    @Override
    public List<RespClubOpenInfo> getMyJoinClubList(int uid) {
        Map map = new HashMap();
        map.put("uid",uid);
        List<RespClubOpenInfo> myJoinClubList = this.clubOpenExtendMapper.getMyJoinClubList(map);
        if (!myJoinClubList.isEmpty()) {
            for (RespClubOpenInfo respClubOpenInfo : myJoinClubList) {
                Integer clubId = respClubOpenInfo.getClubId();
                Integer status = this.getJoinClubStatus(clubId,uid);
                //加入的俱乐部的状态
                respClubOpenInfo.setStatus(status);
                if (respClubOpenInfo!=null) {
                    APIResponse<RespUserInfoBase> apiResponse = this.userServiceFacade.queryUserInfo(respClubOpenInfo.getUid());
                    if (apiResponse.isRet()) {
                        respClubOpenInfo.setPresidentName(apiResponse.getData().getNickName());
                    }else{
                        respClubOpenInfo.setPresidentName("");
                    }
                    respClubOpenInfo.setMemberCount(this.clubMemberService.countClubMembers(respClubOpenInfo.getClubId(), true));

                }
            }
        }
        return myJoinClubList;
    }

    /**
     * 我加入的和我创建的俱乐部中，积分排名最高的
     */
    @Override
    public int getMaxRankingOfMyClubs(int uid){

        TbClubExample clubExample = new TbClubExample();
        clubExample.createCriteria().andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClub> clubs = new ArrayList<>();
        List<TbClub> mycreated = clubMapper.selectByExample(clubExample);
        if (mycreated != null && mycreated.size()>0){
            clubs = mycreated;
        }
        TbClubMemberExample clubMemberExample = new TbClubMemberExample();
        clubMemberExample.createCriteria().andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(clubMemberExample);
        if (clubMembers != null && clubMembers.size() > 0){
            for (TbClubMember member : clubMembers){
                TbClub tbClub = clubMapper.selectByPrimaryKey(member.getClubId());
                if (tbClub != null){
                    clubs.add(tbClub);
                }
            }
        }
        Integer maxRanking = null;
        for (TbClub club : clubs){
            int ranking = clubService.getClubRanking(club.getId(), club.getCityId());
            if (ranking < maxRanking){
                maxRanking = ranking;
            }
        }
        return maxRanking;
    }

    @Override
    public int getMaxRankingOfMyClubs(int uid, int sportTypeId) {
        TbClubExample clubExample = new TbClubExample();
        clubExample.createCriteria()
                .andUidEqualTo(uid)
                .andClubTypeEqualTo(sportTypeId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClub> clubs = new ArrayList<>();
        List<TbClub> mycreated = clubMapper.selectByExample(clubExample);
        if (mycreated != null && mycreated.size()>0){
            clubs = mycreated;
        }
        TbClubMemberExample clubMemberExample = new TbClubMemberExample();
        clubMemberExample.createCriteria().andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(clubMemberExample);
        if (clubMembers != null && clubMembers.size() > 0){
            for (TbClubMember member : clubMembers){
                TbClub tbClub = clubMapper.selectByPrimaryKey(member.getClubId());
                if (tbClub != null && tbClub.getClubType().intValue() == sportTypeId){
                    clubs.add(tbClub);
                }
            }
        }
        List<Integer> rankingList = new ArrayList<>();
        for (TbClub club : clubs){
            int ranking = clubService.getClubRanking(club.getId(), club.getCityId());
            rankingList.add(ranking);
        }
        if (rankingList.size() == 0){
            return 0;
        }
        return Collections.min(rankingList);
    }

    /**
     * 我创建的俱乐部总数
     * @param uid
     * @return
     */
    @Override
    public int getMyManageClubCount(int uid) {
        Map map = new HashMap();
        map.put("uid",uid);
        List<RespClubOpenInfo> myManageClubList = this.clubOpenExtendMapper.getMyManageClubList(map);
        return myManageClubList.size();
    }

    /**
     * 我加入的俱乐部总数
     * @param uid
     * @return
     */
    @Override
    public int getMyJoinClubCount(int uid) {
        Map map = new HashMap();
        map.put("uid",uid);
        List<RespClubOpenInfo> myJoinClubList = this.clubOpenExtendMapper.getMyJoinClubList(map);
        return myJoinClubList.size();
    }

    @Override
    public PageObj<List<RespClubActivity>> selectActivityRecommend(Integer cityId, Integer categoryId, Integer  pageNum, Integer pageSize)
    {
        int total = clubActivityMapper.countRecommends(cityId, categoryId);
        Limit limit = Limit.buildLimit(pageNum + 1, pageSize);
        List<TbClubActivity> clubActivities =
                clubActivityMapper.selectRecommends(cityId, categoryId,
                        limit.getStart(), limit.getSize());
        if (null == clubActivities || clubActivities.size() == 0)
        {
            return null;
        }
        List<RespClubActivity> result = new ArrayList<RespClubActivity>();
        //有推荐的活动
        List<Integer> ids = new ArrayList<Integer>();
        for(TbClubActivity tbClubActivity : clubActivities){
            if(null == tbClubActivity.getActivityId() || tbClubActivity.getActivityId() == 0)
            {
                continue;
            }
            ids.add(tbClubActivity.getActivityId());
        }
        Map<Integer, ActivityInfo> infos = activityOpenService.queryActivityMapList(ids);
        if(null == infos)
        {
            return null;
        }
        for(TbClubActivity tbClubActivity : clubActivities)
        {
            if(null == tbClubActivity.getActivityId() || tbClubActivity.getActivityId() == 0)
            {
                continue;
            }
            //俱乐部信息
            RespClubActivity resp = new RespClubActivity();
            resp.setCurTime(new Date());
            copyPropertyForRespClubActivity(resp,
                    tbClubActivity, infos.get(tbClubActivity.getActivityId()), null);
            result.add(resp);
        }
        return PageObj.create(total, pageNum + 1, pageSize, result);
    }

    private void copyPropertyForPlace(RespClubActivity respClubActivity,
                                                 TbClubActivity tbClubActivity,
                                                 ActivityInfo activityInfo) {
        //活动海报
        RespActivityPoster respActivityPoster = new RespActivityPoster();
        Integer posterPicId = 0;
        if (activityInfo != null) {
            posterPicId = activityInfo.getPosterPicId();
        }
        TbActivityPoster tbActivityPoster = null;
        if (null != posterPicId) {
            tbActivityPoster = tbActivityPosterMapper.selectByPrimaryKey(posterPicId);
            if (null != tbActivityPoster) {
                BeanCopierUtils.copyProperties(tbActivityPoster, respActivityPoster);
            }
        }
        if (null != activityInfo) {
            BeanCopierUtils.copyProperties(activityInfo, respClubActivity);
            respClubActivity.setRespActivityPoster(respActivityPoster);
        }

        if (null != tbClubActivity) {
            BeanCopierUtils.copyProperties(tbClubActivity, respClubActivity);
            respClubActivity.setFemaleMemberFee(tbClubActivity.getFemaleMemberFee());
            respClubActivity.setIsSame(ActivityUtils.isSamePrice(tbClubActivity));
            respClubActivity.setPrice(ActivityUtils.getLowestPrice(tbClubActivity));
        }
        respClubActivity.setIsSettle(tbClubActivity.getIsSettle().intValue());
        respClubActivity.setId(respClubActivity.getActivityId());
        respClubActivity.setCurTime(new Date());
        if (activityInfo != null && null == activityInfo.getPlaceId()
                && null == activityInfo.getPlaceAddress()) {
            return;
        }
    }

    /**
     * 给返回协议对象赋值
     */
    private void copyPropertyForRespClubActivity(RespClubActivity respClubActivity,
                                                 TbClubActivity tbClubActivity,
                                                 ActivityInfo activityInfo, TbClub tbClub) {
        //活动海报
        RespActivityPoster respActivityPoster = new RespActivityPoster();
        Integer posterPicId = 0;
        if (activityInfo != null) {
            posterPicId = activityInfo.getPosterPicId();
        }
        TbActivityPoster tbActivityPoster = null;
        if (null != posterPicId) {
            tbActivityPoster = tbActivityPosterMapper.selectByPrimaryKey(posterPicId);
            if (null != tbActivityPoster) {
                BeanCopierUtils.copyProperties(tbActivityPoster, respActivityPoster);
            }
        }
        if (null != activityInfo) {
            BeanCopierUtils.copyProperties(activityInfo, respClubActivity);
            respClubActivity.setRespActivityPoster(respActivityPoster);
        }

        if (null != tbClubActivity) {
            BeanCopierUtils.copyProperties(tbClubActivity, respClubActivity);
            respClubActivity.setFemaleMemberFee(tbClubActivity.getFemaleMemberFee());
            BigDecimal femaleMemberFee = tbClubActivity.getFemaleMemberFee();
            BigDecimal maleMemberFee = tbClubActivity.getMaleMemberFee();
            BigDecimal femaleFee = tbClubActivity.getFemaleFee();
            BigDecimal maleFee = tbClubActivity.getMaleFee();
            respClubActivity.setIsSame(ActivityUtils.isSamePrice(tbClubActivity));
            respClubActivity.setPrice(ActivityUtils.getLowestPrice(tbClubActivity));
        }
        if (null != tbClub) {
            respClubActivity.setClubId(tbClub.getId());
            respClubActivity.setClubName(tbClub.getClubName());
            respClubActivity.setLogoUrl(tbClub.getLogoUrl());
        }
        respClubActivity.setIsSettle(tbClubActivity.getIsSettle() == null ? 0 : tbClubActivity.getIsSettle().intValue());
        respClubActivity.setId(respClubActivity.getActivityId());
        respClubActivity.setCurTime(new Date());
        if (activityInfo != null && null == activityInfo.getPlaceId()
                && null == activityInfo.getPlaceAddress()) {
            return;
        }
        //todo 场馆
        List<Integer> placeIdList = new ArrayList<>();
        if (activityInfo != null){
            placeIdList.add(activityInfo.getPlaceId());
        }
        Map<Integer, PlaceDubboProvider> map = placeClient.getPlaceListByPlaceId(placeIdList);
        if(!map.isEmpty()){
            PlaceDubboProvider placeDubboProvider = map.get(activityInfo.getPlaceId());
            respClubActivity.setPlaceDubboProvider(placeDubboProvider);
        }
    }

    private static Double mathUtil(List<Double> doubles) {
        Double lowest = 0.00;
        for (int i = 0; i < doubles.size(); i++) {
            if (i == 0) {
                lowest = doubles.get(i);
            } else {
                if (doubles.get(i) < lowest) {
                    lowest = doubles.get(i);
                }
            }
        }
        return lowest;
    }

    @Override
    public RespLatesActivityInfo latestActivityListForPage(Integer pageNum, Integer pageSize) {
        return null;
    }

    /**
     * 获取用户俱乐部的状态
     * @param clubId
     * @param uid
     * @return
     */
    public int getJoinClubStatus(int clubId, int uid){
        TbClubMemberApplyExample example = new TbClubMemberApplyExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andUidEqualTo(uid)
                .andStatusNotEqualTo((byte)2) //拒绝加入的不显示出来
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMemberApply> applies = clubMemberApplyMapper.selectByExample(example);
        if (applies == null || applies.isEmpty()){
            return -1;
        }
        return applies.get(0).getStatus();
    }

    /**
     * 申请加入俱乐部
     * @param uid       用户id
     * @param clubId    俱乐部id
     * @param remark    申请加入的备注
     * @return
     */
    @Override
    public APIResponse applyJoinClub(int uid, int clubId, String remark, int larkAppId){

        boolean isMember = clubMemberService.isClubMember(uid, clubId);
        if (isMember){
            return APIResponse.returnFail(100, "已经是俱乐部成员，不可再次申请");
        }
        boolean isApplied = clubMemberService.isApplyJoinClub(uid, clubId, null);
        if (isApplied){
            return APIResponse.returnFail(101, "已经申请加入，正在审核中");
        }
        boolean ret = clubMemberService.applyJoinClub(uid, clubId, remark, larkAppId);
        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub != null) {
            int joinType = tbClub.getJoinType();
            if (ret && joinType == 1) {
                return APIResponse.returnFail(102, "申请加入成功，等待审核");
            }
        }

        return APIResponse.returnSuccess();
    }

    @Override
    public List<RespClubMember> searchClubMember(int clubId, String keyword) {
        List<RespClubMember> clubMembers = clubMemberService.searchClubMember(clubId, keyword, false);
        Collections.sort(clubMembers, new Comparator<RespClubMember>() {
            @Override
            public int compare(RespClubMember o1, RespClubMember o2) {
                return o1.getPriority() - o2.getPriority();
            }
        });
        return clubMembers;
    }

    @Override
    public APIResponse<List<RespClubMovement>> searchClubMovmentToUserModele(List<ReqClubMovement> reqClubMovements) {
        List<Integer> activityIds=new ArrayList<>();
        for (ReqClubMovement reqClubMovement:reqClubMovements){
            activityIds.add(reqClubMovement.getActivityId());
        }
        if (com.quanyan.club.pullclub.utils.CollectionUtils.isEmpty(activityIds)){
            return null;
        }
        TbActivityExample tbActivityExample=new TbActivityExample();
        tbActivityExample.createCriteria().andIdIn(activityIds);
        List<TbActivity> tbActivityList=tbActivityMapper.selectByExample(tbActivityExample);
        if (com.quanyan.club.pullclub.utils.CollectionUtils.isEmpty(tbActivityList)){
            return null;
        }
        List<RespClubMovement> clubActivityInfos=new ArrayList<>();
        List<Integer> posterIds=new ArrayList<>();
        List<Integer> palceIds=new ArrayList<>();
        for (TbActivity tbActivity:tbActivityList){
            RespClubMovement clubActivityInfo=new RespClubMovement();
            clubActivityInfo.setActivityName(tbActivity.getName());//活动名称
            clubActivityInfo.setStartTime(tbActivity.getStartTime());//活动开始时间
            clubActivityInfo.setEndTime(tbActivity.getEndTime());//活动结束
            clubActivityInfo.setActivityId(tbActivity.getId());//活动id
            clubActivityInfo.setCategoryId(tbActivity.getCategoryId());//俱乐部分类
            clubActivityInfo.setPostId(tbActivity.getPosterPicId());//海报id
            clubActivityInfo.setAddress(tbActivity.getPlaceAddress());//活动地址
            clubActivityInfo.setPlaceId(tbActivity.getPlaceId());//场馆id
            clubActivityInfos.add(clubActivityInfo);

            posterIds.add(tbActivity.getPosterPicId());
            palceIds.add(tbActivity.getPlaceId());
        }
        if (com.quanyan.club.pullclub.utils.CollectionUtils.isNotEmpty(posterIds)){
            TbActivityPosterExample tbActivityPosterExample=new TbActivityPosterExample();
            tbActivityPosterExample.createCriteria().andIdIn(posterIds);
            List<TbActivityPoster> tbActivityPosters=tbActivityPosterMapper.selectByExample(tbActivityPosterExample);
            for (RespClubMovement clubActivityInfo:clubActivityInfos){
                for (TbActivityPoster tbActivityPoster:tbActivityPosters){
                    if (tbActivityPoster.getId().equals(clubActivityInfo.getPostId())){
                        clubActivityInfo.setImageUrl(tbActivityPoster.getUrl());//活动海报
                        break;
                    }
                }
            }
        }
        if (com.quanyan.club.pullclub.utils.CollectionUtils.isNotEmpty(palceIds)){
            if (CollectionUtils.isNotEmpty(palceIds)) {
                Map<Integer, PlaceDubboProvider> placeMap = placeClient.getPlaceListByPlaceId(palceIds);
                logger.warn("---调场馆查询活动地址-------------->>>" + com.github.ltsopensource.core.json.JSON.toJSONString(placeMap));
                if (null != placeMap) {
                    for (RespClubMovement clubActivityInfo : clubActivityInfos) {
                        for (Map.Entry<Integer, PlaceDubboProvider> map : placeMap.entrySet()) {
                            if (clubActivityInfo.getPlaceId().equals(map.getKey())) {
                                clubActivityInfo.setAddress(map.getValue().getAddress());//设置活动地址
                                break;
                            }
                        }
                    }
                }
            }
        }
        return APIResponse.returnSuccess(clubActivityInfos);
    }

    @Autowired
    private TbCityMapper cityMapper;
    @Autowired
    private TbDistrictMapper districtMapper;

    @Override
    public MyNewestClubCard getMyNewestClub(int uid) {
        long start = System.currentTimeMillis();
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        example.setOrderByClause(" create_time desc");
        List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(example);
        if (clubMembers == null || clubMembers.size() == 0){
            return null;
        }
        int totalCount = 0;
        TbClub newestClub = null;
        for (TbClubMember tbClubMember : clubMembers){
            int clubId = tbClubMember.getClubId();
            TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
            if (tbClub == null || tbClub.getIsDelete() == Constants.IS_DELETE_TRUE){
                continue;
            }
            if (newestClub == null){
                newestClub = tbClub;
            }
            totalCount++;
        }
        MyNewestClubCard card = new MyNewestClubCard();
        if (newestClub == null){
            return null;
        }
        card.setTotalCount(totalCount);
        card.setClubName(newestClub.getClubName());
        card.setClubLogo(newestClub.getLogoUrl());
        example.clear();
        example.createCriteria()
                .andClubIdEqualTo(newestClub.getId()).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        card.setMemberCount(clubMemberMapper.countByExample(example));
        TbCity city = cityMapper.selectByPrimaryKey(newestClub.getCityId());
        if (city != null) {
            card.setCityName(city.getName());
        }
        TbDistrict district = districtMapper.selectByPrimaryKey(newestClub.getDistrictId());
        if (district != null){
            card.setDistinctName(district.getName());
        }
        card.setMyLastActivity(this.getMyLastActivity(uid));
        long end = System.currentTimeMillis();
        logger.warn("------------------" + (end - start) + "------------------");
        return card;
    }

    /**
     *  俱乐部推荐
     * @param clubTypeId    栏目id
     * @param lat           纬度
     * @param lng           经度
     * @param raduis        搜索半径
     * @param size          返回俱乐部个数
     * @return
     */
    @Override
    public List<RespClubBaseInfo> clubRecommendBasePOI(int uid, int clubTypeId, double lat, double lng, double raduis, int size, int soryBy){
        logger.warn("club poi rec: 方法开始");
        long start = System.currentTimeMillis();
        if (clubTypeId == 0 || lat == 0 || lng == 0 || raduis == 0 || size == 0){
            return new ArrayList<>();
        }
        ReqClubSearch search = new ReqClubSearch();
        search.setClubTypeId(clubTypeId);
        search.setLat(lat);
        search.setLng(lng);
        search.setDistance(raduis);
        search.setSortBy(soryBy);    //按距离排序
        search.setPageNo(0);
        search.setPageSize(size);    //最大500条
        PageObj<List<RespClubBaseInfo>> result = clubSearchBizService.searchClubs(uid,search);
        if (result != null && result.getItems() != null){
            List<RespClubBaseInfo> clubBaseInfoList = result.getItems();
            if (clubBaseInfoList.size() > size){
                clubBaseInfoList = clubBaseInfoList.subList(0, size);
            }
            long end = System.currentTimeMillis();
            logger.warn("-----计算时间-------------" + (end - start) + "------------------");
            logger.warn("club poi rec: 返回：{}", JSON.toJSONString(clubBaseInfoList));
            return clubBaseInfoList;
        }
        return new ArrayList<>();
    }
}
